package top.doe.rpc.base;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import top.deo.rpc.base.common.*;

public class SystemBServer {

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(9099);


        while(true){
            Socket socket = serverSocket.accept();

            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            // 读取请求端传入的request
            Request request = (Request) in.readObject();

            // 提取request中的调用信息
            String modelClassName = request.getModelClassName();
            String methodName = request.getMethodName();
            Class<?>[] parameterTypes = request.getParameterTypes();
            Object[] parameters = request.getParameters();

            // 反射调用本系统中的目标模块目标方法
            Class<?> aClass = Class.forName(modelClassName);
            Object moduleInstance = aClass.newInstance();
            Method method = aClass.getMethod(methodName, parameterTypes);

            Object result = method.invoke(moduleInstance, parameters);

            // 发送响应
            Response response = new Response(result, null, 0);
            out.writeObject(response);

            out.flush();

            in.close();
            out.close();
            socket.close();


        }



    }

}
